package com.education.welco.controller;


import com.education.common.config.BusinessException;
import com.education.common.config.CommonErrorCode;
import com.education.common.pojo.AjaxResult;
import com.education.common.pojo.SysInfoMsg;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.StringUtils;
import com.education.welco.feign.InfoMsgFeign;
import com.education.welco.feign.userFeign;
import com.education.welco.pojo.*;
import com.education.welco.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 教师 信息操作处理
 *
 * @author d
 * @date 2020-05-08
 */
@RestController
@RequestMapping("/tTeacher")
public class TTeacherController {

    private static SimpleDateFormat DATE_FROMAT = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    @Autowired
    private ITTeacherService teacherService;
    @Autowired
    private ISCatalogMenuService catalogMenuService;
    @Autowired
    private InfoMsgFeign msgFeign;
    @Autowired
    private ITSchooldeptService schooldeptService;
    @Autowired
    private userFeign userFeign;
    @Autowired
    private ITTeacherClassService teacherClassService;
    @Autowired
    private ITClassService classService;
    @Autowired
    private ITStudentService studentService;


    /** 新添加教师管理 */
    /**
     * 查询
     */
    @GetMapping("/list2")
    public ApiReturnObject list2(TTeacher tTeacher, Integer pageNum, Integer pageSize) {
        if (pageNum != null && pageSize != null) PageHelper.startPage(pageNum, pageSize);
        List<TTeacher> tTeachers = teacherService.selectTTeacherListOther2(tTeacher);
        for (TTeacher teacher : tTeachers) {
            //格式化创建时间
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(teacher.getCreateTime());
            teacher.setTime(dateString);

            //拼接管理班级字符串
            List<TClass> tClasses = classService.selectTClassByTeaId(teacher.getId());
            String s = "";
            List<Integer> classIdList2 = new ArrayList<>();
            if (tClasses.size() > 0) {
                for (int i = 0; i < tClasses.size(); i++) {
                    if (i == tClasses.size() - 1) {
                        s = s + tClasses.get(i).getClassName();
                    } else {
                        s = s + tClasses.get(i).getClassName() + ",";
                    }
                }
                classIdList2 = tClasses.parallelStream().map(tClass -> tClass.getId()).collect(Collectors.toList());
            }
            teacher.setClassString(s);
            teacher.setClassIdList2(classIdList2);
        }
        PageInfo<TTeacher> pageInfo = new PageInfo<>(tTeachers);
        return new ApiReturnObject("200", "查询成功", pageInfo);
    }


    /**
     * 详情
     */
    @GetMapping("/selectOne")
    public ApiReturnObject selectOne(Integer id) {
        if (id != null) {
            TTeacher tTeacher = teacherService.selectTTeacherById(id);
            //所带班级  在中间表中查出所带班级
            List<Integer> classIds = teacherClassService.selectTTeacherClassByTeaId(tTeacher.getId());
            List<List<Integer>> lists = new ArrayList<>();
            //和其上级部门组成数组进行返回
            for (Integer classId : classIds) {
                ArrayList<Integer> arrayList = Lists.newArrayList();
                TClass tClass = classService.selectTClassById(classId);
                if (StringUtils.isNull(tClass)) {
                    continue;
                }
                Integer deptId = tClass.getDeptId();
                arrayList.add(deptId);
                arrayList.add(classId);
                lists.add(arrayList);
            }
            tTeacher.setClassIdList(lists);
            return new ApiReturnObject("200", "查询成功", tTeacher);
        }
        return new ApiReturnObject("201", "缺少参数id", "");
    }

    /**
     * 导入教师信息
     */
    @SuppressWarnings("all")
    @RequestMapping(value = "/threeImport", method = RequestMethod.POST)
    public AjaxResult threeExImport(@RequestParam("file") MultipartFile file,
                                    @RequestParam("schoolId") Integer schoolId) {
        String fileName = file.getOriginalFilename();
        try {
            Boolean a = teacherService.threeBatchQuesionImport(fileName, file, schoolId);
            if (a) {
                return AjaxResult.success("导入成功！");
            } else {
                return AjaxResult.error(201, "导入失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(201, e.getMessage());
        }
    }

    /**
     * 教务主任添加老师
     *
     * @param tTeacher
     * @return
     */
    @PostMapping("/add2")
    public ApiReturnObject add(@RequestBody TTeacher tTeacher) {
        int userId = 0;
        //远程调用user模块进行添加用户数据
        ApiReturnObject apiReturnObject = userFeign.addUser(tTeacher.getPhone(), "123456", tTeacher.getSchoolId(), tTeacher.getTId(), tTeacher.getTeacherName());
        //用户表已存在该手机号，状态为(学生、教师、教务主任、管理员)
        if ("201".equals(apiReturnObject.getCode()) && StringUtils.isNotBlank((String) (((Map) apiReturnObject.getReturnObject()).get("type"))) && Arrays.asList("1", "2", "3", "4").contains(((Map) apiReturnObject.getReturnObject()).get("type"))) {
            return new ApiReturnObject("201", "该手机号已被使用", "");
        }
        if ("201".equals(apiReturnObject.getCode()) && StringUtils.isBlank((String) (((Map) apiReturnObject.getReturnObject()).get("type")))) {
            userId = (int) (((Map) apiReturnObject.getReturnObject()).get("id"));
        }
        if ("200".equals(apiReturnObject.getCode())) {
            userId = (int) apiReturnObject.getReturnObject();
        }
        /*TTeacher tTeacher1 = TTeacher.builder().phone(tTeacher.getPhone()).build();
        List<TTeacher> tTeachers = teacherService.selectTTeacherList(tTeacher1);
        if (tTeachers.size() > 0) {
            return new ApiReturnObject("201", "该手机号已存在", "");
        }*/
        //用户表不存在新增
        /*TTeacher build = TTeacher.builder().idcardno(tTeacher.getIdcardno()).build();
        List<TTeacher> builds = teacherService.selectTTeacherList(build);
        if (builds.size() > 0) {
            return new ApiReturnObject("201", "该身份证号已存在", "");
        }*/
        tTeacher.setUserId(userId);
        tTeacher.setCreateTime(new Date());
        //根据部门id设置学校id
        tTeacher.setSchoolId(tTeacher.getSchoolId());
        teacherService.insertTTeacher(tTeacher);
        Integer teacherId = tTeacher.getId();
        //修改教师班级中间表数据
        if (tTeacher.getClassIdList() != null && tTeacher.getClassIdList().size() > 0) {
            //先删除原先数据
            teacherClassService.deleteTTeacherClassById(teacherId);
            //遍历添加 添加新的关联数据
            for (List<Integer> integers : tTeacher.getClassIdList()) {
                //拿到最后一级的班级id
                Integer classId = integers.get(integers.size() - 1);
                TTeacherClass teacherClass = new TTeacherClass();
                teacherClass.setTeacherId(teacherId);
                teacherClass.setClassId(classId);
                teacherClassService.insertTTeacherClass(teacherClass);
            }
        }
        //新增app端的数据接收处理
        if (tTeacher.getClassIdList2() != null && tTeacher.getClassIdList2().size() > 0) {
            //先删除原先数据
            teacherClassService.deleteTTeacherClassById(tTeacher.getId());
            //遍历添加 添加新的关联数据
            for (Integer integers : tTeacher.getClassIdList2()) {
                //拿到最后一级的班级id
                Integer classId = integers;
                TTeacherClass teacherClass = new TTeacherClass();
                teacherClass.setTeacherId(tTeacher.getId());
                teacherClass.setClassId(classId);
                teacherClassService.insertTTeacherClass(teacherClass);
            }
        }
        //用户表已存在改手机号，状态为普通用户 更改用户表用户状态
        if ("201".equals(apiReturnObject.getCode()) && StringUtils.isBlank((String) (((Map) apiReturnObject.getReturnObject()).get("type")))) {
            studentService.updateInfoForUser(userId, null, tTeacher.getSchoolId(), 2, 2);
            studentService.insertUserRoleInUser(userId, 2);
        }
        return new ApiReturnObject("200", "添加成功", "");
    }

    /**
     * 修改
     */
    @PostMapping("/update2")
    public ApiReturnObject update2(@RequestBody TTeacher tTeacher) {
        //远程调用修改教师关联用户信息    判断手机号是否改变
        TTeacher tTeacher1 = teacherService.selectTTeacherById(tTeacher.getId());
        if (!tTeacher1.getPhone().equals(tTeacher.getPhone())) {
            ApiReturnObject apiReturnObject = userFeign.updateTea(tTeacher1.getUserId(), tTeacher.getPhone());
        }
        teacherService.updateTTeacher(tTeacher);
        //修改教师班级中间表数据
        if (tTeacher.getClassIdList() != null && tTeacher.getClassIdList().size() > 0) {
            //先删除原先数据
            teacherClassService.deleteTTeacherClassById(tTeacher.getId());
            //遍历添加 添加新的关联数据
            for (List<Integer> integers : tTeacher.getClassIdList()) {
                //拿到最后一级的班级id
                Integer classId = integers.get(integers.size() - 1);
                TTeacherClass teacherClass = new TTeacherClass();
                teacherClass.setTeacherId(tTeacher.getId());
                teacherClass.setClassId(classId);
                teacherClassService.insertTTeacherClass(teacherClass);
            }
        }
        //标记：新增app端的数据接收处理
        if (tTeacher.getClassIdList2() != null && tTeacher.getClassIdList2().size() > 0) {
            //先删除原先数据
            teacherClassService.deleteTTeacherClassById(tTeacher.getId());
            //遍历添加 添加新的关联数据
            for (Integer integers : tTeacher.getClassIdList2()) {
                //拿到最后一级的班级id
                Integer classId = integers;
                TTeacherClass teacherClass = new TTeacherClass();
                teacherClass.setTeacherId(tTeacher.getId());
                teacherClass.setClassId(classId);
                teacherClassService.insertTTeacherClass(teacherClass);
            }
        }
        return new ApiReturnObject("200", "修改成功", "");
    }

    /**
     * 添加和删除头像
     *
     * @param tTeacher
     * @return
     */
    @PostMapping("/updateImg")
    public ApiReturnObject updateImg(@RequestBody TTeacher tTeacher) {
        tTeacher.setTeacherImage(tTeacher.getImgUrl());
        teacherService.updateTTeacher(tTeacher);
        return new ApiReturnObject("200", "修改成功", "");
    }

    /**
     * 添加和删除头像
     *
     * @param tTeacher
     * @return
     */
    @PostMapping("/delImg")
    public ApiReturnObject delImg(@RequestBody TTeacher tTeacher) {
        TTeacher tTeacher1 = teacherService.selectTTeacherById(tTeacher.getId());
        //删除七牛云资源
        //QiniuUtil.deleteFileFromQiniu(tTeacher1.getTeacherImage());
        tTeacher.setTeacherImage("");
        teacherService.updateTTeacher(tTeacher);
        return new ApiReturnObject("200", "删除成功", "");
    }

    /**
     * 删除教师
     *
     * @param tea
     * @return
     */
    @PostMapping("/del")
    public ApiReturnObject del(@RequestBody TTeacher tea) {
        Integer id = tea.getId();
        //删除老师之前 先删除掉老师对应的用户
        TTeacher tTeacher = teacherService.selectTTeacherById(id);
        //更改用户表的用户状态
        if (tTeacher.getUserId() != null) {
            userFeign.delPCUser(tTeacher.getUserId());
        }
        //删除老师和班级的关联表数据
        teacherClassService.deleteTTeacherClassById(id);
        teacherService.deleteTTeacherByIds(id + "");
        return new ApiReturnObject("200", "删除成功", "");
    }

    /**
     * 查询与该教师有关的首页数据
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("list")
    public ApiReturnObject list(Integer userId, Integer pageNum, Integer pageSize) {
        //根据课程id 查询出 之下的目录
        if (userId != null) {
            Integer i = 1;
            HashMap<String, Object> map = new HashMap<>();
            //返回我的消息列表
            List<SysInfoMsg> sysInfoMsgs = msgFeign.queryMsg(userId);
            map.put("sysInfoMsgs", sysInfoMsgs);
            //查询出备课列表以及在授班级
            SCatalogMenu catalogMenu = new SCatalogMenu();
            catalogMenu.setParentId(0);
            catalogMenu.setUserId(userId);
            //我的课程列表
            if (pageNum != null && pageSize != null) {
                PageHelper.startPage(pageNum, pageSize);
                i = ((pageNum - 1) * pageSize) + 1;
            }
            List<SCatalogMenu> catalogMenuList = catalogMenuService.selectSCatalogMenuList(catalogMenu);
            //遍历设置下标
            for (SCatalogMenu sCatalogMenu : catalogMenuList) {
                sCatalogMenu.setSubscript(i);
                i = i + 1;
            }
            PageInfo<SCatalogMenu> pageInfo = new PageInfo<>(catalogMenuList);
            map.put("catalogMenuList", pageInfo);
            /*if (catalogMenuList.size() > 8) {
                //取前八条数据
                List<SCatalogMenu> newList = catalogMenuList.subList(0, 8);
                map.put("catalogMenuList",newList);
                return new ApiReturnObject("200", "查询成功", map);
            }*/
            return new ApiReturnObject("200", "查询成功", map);
        } else {
            return new ApiReturnObject("201", "缺少userId参数", "");
        }
    }

    /**
     * 教务端--教室管理--查询
     *
     * @param tTeacher
     * @return
     * @throws ParseException
     */
    @GetMapping("/selectAll")
    public ApiReturnObject selectAll(TTeacher tTeacher) throws ParseException {
        if (tTeacher.getSchoolId() == null) {
            throw new BusinessException(CommonErrorCode.E_200101);
        }
        List<TTeacher> teacherList = teacherService.selectTTeacherList(tTeacher);
        for (TTeacher teacher : teacherList) {
            teacher.setTime(DATE_FROMAT.format(teacher.getCreateTime()));

            //查询老师所属部门
            TSchooldept one = schooldeptService.selectTSchooldeptById(teacher.getDepartId());//三级专业
            TSchooldept two = schooldeptService.selectTSchooldeptById(one.getParentId());//二级系
            StringBuilder builder = new StringBuilder();
            StringBuilder append = builder.append(two.getDeptName()).append("--").append(one.getDeptName());
            teacher.setDepart(append.toString());
        }
        return new ApiReturnObject("200", "success", teacherList);
    }

    /**
     * 教务端--教室管理--修改
     *
     * @param tTeacher
     * @return
     * @throws BusinessException
     */
    @PutMapping("/update")
    public ApiReturnObject update(@RequestBody TTeacher tTeacher) throws BusinessException {
        teacherService.updateTTeacher(tTeacher);
        return new ApiReturnObject("200", "success", "");
    }

    /**
     * 教务端--教室管理--添加
     *
     * @param tTeacher
     * @return
     * @throws BusinessException
     */
    @PostMapping("/insert")
    public ApiReturnObject insert(@RequestBody TTeacher tTeacher) throws BusinessException {
        tTeacher.setCreateTime(new Date());
        teacherService.insertTTeacher(tTeacher);
        return new ApiReturnObject("200", "success", "");
    }

    /**
     * 教务端--教室管理--删除
     *
     * @param ids
     * @return
     * @throws BusinessException
     */
    @DeleteMapping("/delete")
    public ApiReturnObject delete(String[] ids) throws BusinessException {
        for (String id : ids) {
            teacherService.deleteTTeacherByIds(id);
        }
        return new ApiReturnObject("200", "success", "");
    }
}